package com.general.framework.example.contractPdf;

import com.itextpdf.text.BadElementException;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import com.itextpdf.text.Image;
import java.util.ArrayList;
import java.util.List;


    /**
     * 切割图片
     * @param Path  图片路径
     * @param n 切割份数
     */
    // public static Image[] slicingImages(String Path, int n) throws IOException, BadElementException {
    //     Image[] nImage = new Image[n];
    //     ByteArrayOutputStream out = new ByteArrayOutputStream();
    //     BufferedImage img = ImageIO.read(new File(Path));
    //     int h = img.getHeight();
    //     int w = img.getWidth();
    //
    //     int sw = w/n;
    //     for(int i=0;i<n;i++){
    //         BufferedImage subImg;
    //         if(i==n-1){//最后剩余部分
    //             subImg = img.getSubimage(i * sw, 0, w-i*sw, h);
    //         }else {//前n-1块均匀切
    //             subImg = img.getSubimage(i * sw, 0, sw, h);
    //         }
    //
    //         ImageIO.write(subImg,Path.substring(Path.lastIndexOf('.')+1),out);
    //         nImage[i] = Image.getInstance(out.toByteArray());
    //         out.flush();
    //         out.reset();
    //     }
    //     return nImage;
    // }

    /**
     *  盖骑缝章
     *
     */
    // public static void stamperCheckMarkPDF(String infilePath,String outFilePath,String picPath) throws IOException, DocumentException {
    //     PdfReader reader = new PdfReader(infilePath);//选择需要印章的pdf
    //     PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(outFilePath));//加完印章后的pdf
    //
    //     com.itextpdf.text.Rectangle pageSize = reader.getPageSize(1);//获得第一页
    //     float height = pageSize.getHeight();
    //     float width  = pageSize.getWidth();
    //
    //     int nums = reader.getNumberOfPages();
    //     Image[] nImage =  slicingImages(picPath,nums);//生成骑缝章切割图片
    //
    //
    //     for(int n=1;n<=nums;n++){
    //         PdfContentByte over = stamp.getOverContent(n);//设置在第几页打印印章
    //         Image img = nImage[n-1];//选择图片
    //         img.setAbsolutePosition(width-img.getWidth(),height/2-img.getHeight()/2);//控制图片位置
    //         over.addImage(img);
    //     }
    //     stamp.close();
    // }

public class Main {
    public static void main(String[] args) {
        try {
            String infilePath = "D:\\sysapp\\input.pdf"; // 输入PDF文件路径
            String outFilePath = "D:\\sysapp\\output.pdf"; // 输出PDF文件路径
            String picPath = "D:\\sysapp\\seal.png"; // 印章图片路径
            stamperCheckMarkPDF(infilePath, outFilePath, picPath);
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        }
    }

    public static void stamperCheckMarkPDF(String infilePath, String outFilePath, String picPath)
            throws IOException, DocumentException {
        PdfReader reader = new PdfReader(infilePath);
        PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(outFilePath));
        Image[] nImage = slicingImages(picPath, reader.getNumberOfPages());

        for (int n = 0; n < reader.getNumberOfPages(); n++) {
            PdfContentByte over = stamp.getOverContent(n);
            Image img = nImage[n];
            // 设置印章图片的位置，这里以页面底部居中为例
            float x = (reader.getPageSizeWithRotation(n).getWidth() - img.getScaledWidth()) / 2;
            float y = reader.getPageSizeWithRotation(n).getHeight() - img.getScaledHeight() - 20; // 20是印章底部与页面底部的距离
            img.setAbsolutePosition(x, y);
            over.addImage(img);
        }
        stamp.close();
    }

    public static Image[] slicingImage(String picPath, int n) throws IOException, BadElementException {
        List<Image> images = new ArrayList<>();
        BufferedImage img = ImageIO.read(new File(picPath));
        int originalWidth = img.getWidth();
        int originalHeight = img.getHeight();
        int segmentWidth = originalWidth / n; // 假设图片均匀切割

        for (int i = 0; i < n; i++) {
            BufferedImage subImg = img.getSubimage(i * segmentWidth, 0, segmentWidth, originalHeight);
            boolean png = ImageIO.write(subImg, "png", new ByteArrayOutputStream());
            // try (ByteArrayInputStream bis = new ByteArrayInputStream(png)) {
            //     Image image = Image.getInstance(bis.toString());
            //     image.scaleToFit(100, originalHeight); // 设置切割图片的大小
            //     images.add(image);
            // }
        }
        return images.toArray(new Image[0]);
    }
    public static Image[] slicingImages(String picPath, int n) throws IOException, BadElementException {
        File imageFile = new File(picPath);
        BufferedImage img = ImageIO.read(imageFile);
        int originalWidth = img.getWidth();
        int segmentWidth = originalWidth / n;

        List<Image> images = new ArrayList<>(n);
        for (int i = 0; i < n; i++) {
            BufferedImage subImg = img.getSubimage(i * segmentWidth, 0, Math.min(segmentWidth, originalWidth - i * segmentWidth), img.getHeight());
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(subImg, "png", baos);
            byte[] imageBytes = baos.toByteArray();
            baos.close();

            try (InputStream bis = new ByteArrayInputStream(imageBytes)) {
                Image itextImage = Image.getInstance(bis.toString());
                itextImage.scaleToFit(segmentWidth, img.getHeight()); // 根据实际需要调整图片大小
                images.add(itextImage);
            }
        }
        return images.toArray(new Image[0]);
    }
}
